package com.zzyl.nursing.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.domain.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.utils.DateUtils;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.FamilyAddDto;
import com.zzyl.nursing.dto.PropertyMeta;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.RoomTypeMapper;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataResult;
import com.zzyl.nursing.vo.DevicePropertiesVo;
import com.zzyl.nursing.vo.ElderDeviceVo;
import com.zzyl.nursing.vo.FamilyElderVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;

import javax.servlet.http.HttpServletRequest;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private IFamilyMemberElderService familyMemberElderService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private RoomTypeMapper roomTypeMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IoTDAClient client;


    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");
    @Autowired
    private HttpRequestHandlerAdapter httpRequestHandlerAdapter;

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if (ObjectUtil.isEmpty(familyMember)) {
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember, phone);

        //6. 把用户的信息封装到token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", familyMember.getName());
        claims.put("userId", familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Override
    public List<DeviceDataResult> queryDeviceDataList(DeviceDataDto dto) {
        List<DeviceDataResult> list = familyMemberMapper.queryDeviceDataList(dto);
        // 将查询结果存入Map，方便查找
        Map<String, Double> dataMap = new HashMap<>();
        for (DeviceDataResult data : list) {
            dataMap.put(data.getDateTime(), data.getDataValue());
        }

        // 构建24小时完整数据列表，缺失的小时填充0
        List<DeviceDataResult> resultList = new ArrayList<>(24);
        for (int hour = 0; hour < 24; hour++) {
            // 格式化小时为"HH:00"格式
            String hourStr = String.format("%02d:00", hour);

            DeviceDataResult hourlyData = new DeviceDataResult();
            hourlyData.setDateTime(hourStr);
            // 如果有数据则使用数据库值，否则为0
            hourlyData.setDataValue(dataMap.getOrDefault(hourStr, 0.0));

            resultList.add(hourlyData);
        }

        return resultList;
    }

    @Override
    public void addFamilyMember(FamilyAddDto dto) {
        Long id = UserThreadLocal.getUserId();
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .one();
        if(elder==null){
            throw new RuntimeException("该老人不存在");
        }
        FamilyMember familyMember = familyMemberMapper.selectById(id);
        
        // 检查是否已存在相同的关联关系
        FamilyMemberElder existing = familyMemberElderService.lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, familyMember.getId())
                .eq(FamilyMemberElder::getElderId, elder.getId())
                .one();

        // 只有当关系不存在时才插入新记录
        if (existing == null) {
            FamilyMemberElder fme = new FamilyMemberElder();
            fme.setFamilyMemberId(familyMember.getId());
            fme.setElderId(elder.getId());
            fme.setRemark(dto.getRemark());
            fme.setCreateTime(LocalDateTime.now());
            familyMemberElderMapper.insert(fme);
        }

    }

    @Override
    public List<FamilyElderVo> getElders() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> list = familyMemberElderService.lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, userId)
                .list();
        List<FamilyElderVo> familyElderVos = BeanUtil.copyToList(list, FamilyElderVo.class);
        List<Long> elderIds = new ArrayList<>();
        familyElderVos.forEach(k -> {
            Long elderId = k.getElderId();
            elderIds.add(elderId);
        });
        List<Elder> elders = elderService.lambdaQuery()
                .in(Elder::getId, elderIds)
                .list();
        familyElderVos.forEach(k -> {
            elders.forEach(v -> {
                k.setElderName(v.getName());
            });
        });
        return familyElderVos;
    }

    @Override
    public List<ElderDeviceVo> listByPage() {
        Long userId = UserThreadLocal.get();
//        IPage<ElderDeviceVo> page = new Page<>(pageNum,pageSize);
//        Page<ElderDeviceVo> elderDeviceVoPage = familyMemberMapper.selectFamilyMemberPage(userId);
//        List<ElderDeviceVo> records = elderDeviceVoPage.getRecords();
        List<ElderDeviceVo> records = familyMemberMapper.selectFamilyMemberPage(userId);
        return records;

    }

    @Override
    public PropertiesVo<ProVo<DevicePropertiesVo>> getDeviceProperties(Device device) {
        //  查询设备信息（确认设备存在）
        Device one = deviceService.lambdaQuery()
                .eq(Device::getProductKey, device.getProductKey())
                .one();
        if (one == null) {
            throw new RuntimeException("设备不存在");
        }


        //  查询设备影子获取属性值
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(one.getIotId());
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        Map<String, Object> properties = (Map<String, Object>) response.getShadow().get(0).getReported().getProperties();
        String eventTime = response.getShadow().get(0).getReported().getEventTime();

        //  处理时间格式（转换为东八区时间戳）
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
        ZonedDateTime utcTime = ZonedDateTime.parse(eventTime, inputFormatter.withZone(ZoneOffset.UTC));
        ZonedDateTime cstTime = utcTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
        String time = String.valueOf(cstTime.toInstant().toEpochMilli());

        List<DevicePropertiesVo> list = new ArrayList<>();
        //将影子数据装入对象中
        properties.forEach((identifier, value) -> {
        //     从产品模型中获取当前属性的元信息（单位、数据类型）
            DevicePropertiesVo devicePropertiesVo = new DevicePropertiesVo();
            devicePropertiesVo.setIdentifier(identifier);
            // 处理属性值的格式化（根据数据类型转换）
            if (value instanceof Double) {
                DecimalFormat df = new DecimalFormat("0");
                devicePropertiesVo.setValue(df.format((Double) value));
            } else {
                devicePropertiesVo.setValue(value != null ? value.toString() : "");
            }
            try {
                // 调用华为云SDK查询产品详情,从产品中获取属性名称、单位、数据类型
                ShowProductRequest productRequest = new ShowProductRequest();
                productRequest.setProductId(one.getProductKey());
                ShowProductResponse productResponse = client.showProduct(productRequest);

                if(productResponse.getServiceCapabilities() != null) {
                    productResponse.getServiceCapabilities().forEach(v -> {
                        if(v.getProperties() != null) {
                            v.getProperties().forEach(k -> {
                                if(k.getPropertyName().equals(identifier)) {
                                    devicePropertiesVo.setName(k.getDescription()); // 从产品模型获取属性名称
                                    devicePropertiesVo.setUnit(k.getUnit()); // 从产品模型获取单位
                                    devicePropertiesVo.setDataType(k.getDataType()); // 从产品模型获取数据类型
                                }
                            });
                        }
                    });


                }

            } catch (Exception e) {
                throw new RuntimeException("查询产品模型失败：" + e.getMessage(), e);
            }
            devicePropertiesVo.setTime(time);
            list.add(devicePropertiesVo);
        });


        // 按固定顺序排序
        Map<String, Integer> orderMap = new HashMap<>();
        orderMap.put("BodyTemp", 1);
        orderMap.put("xueyang", 2);
        orderMap.put("BatteryPercentage", 3);
        orderMap.put("HeartRate", 4);
        list.sort((a, b) -> {
            Integer orderA = orderMap.getOrDefault(a.getIdentifier(), 0);
            Integer orderB = orderMap.getOrDefault(b.getIdentifier(), 0);
            return orderA.compareTo(orderB);
        });

        // 组装返回结果
        ProVo<DevicePropertiesVo> proVo = new ProVo();
        proVo.setPropertyStatusInfo(list);
        PropertiesVo<ProVo<DevicePropertiesVo>> result = new PropertiesVo<>();
        result.setList(proVo);
        return result;
    }

    @Override
    public List<DeviceDataByWeekResult> queryDeviceDataByWeekList(DeviceDataDto dto) {
        // 1. 从数据库查询指定时间范围内的数据
        List<DeviceDataByWeekResult> list = familyMemberMapper.queryDeviceDataByWeekList(dto);

        // 2. 将查询结果存入Map，key为"MM.dd"格式的日期，方便查找
        Map<String, Double> dataMap = new HashMap<>();
        for (DeviceDataByWeekResult data : list) {
            // 假设数据库查询结果中的dateTime是"yyyy-MM-dd"格式
            // 转换为"MM.dd"格式作为map的key
            String originalDate = data.getDateTime();
            String formattedDate = formatToMmDd(originalDate);
            dataMap.put(formattedDate, data.getDataValue());
        }

        // 3. 构建时间范围内的完整日期列表（7天）
        List<DeviceDataByWeekResult> resultList = new ArrayList<>(7);
        // 获取查询的开始时间和结束时间（毫秒值）
        Long startTime = dto.getStartTime();
        Long endTime = dto.getEndTime();

        // 转换为LocalDate
        LocalDate startDate = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endDate = Instant.ofEpochMilli(endTime).atZone(ZoneId.systemDefault()).toLocalDate();

        // 循环填充每天数据
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            // 格式化为"MM.dd"
            String dateStr = formatToMmDd(currentDate);

            DeviceDataByWeekResult dailyData = new DeviceDataByWeekResult();
            dailyData.setDateTime(dateStr);
            // 有数据则使用数据库值，否则为0
            dailyData.setDataValue(dataMap.getOrDefault(dateStr, 0.0));

            resultList.add(dailyData);
            // 日期加1天
            currentDate = currentDate.plusDays(1);
        }

        return resultList;
    }


    /**
     * 将LocalDate转换为"MM.dd"格式
     */
    private String formatToMmDd(LocalDate date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.dd");
        return date.format(formatter);
    }

    /**
     * 将"yyyy-MM-dd"字符串转换为"MM.dd"格式
     */
    private String formatToMmDd(String dateStr) {
        LocalDate date = LocalDate.parse(dateStr);
        return formatToMmDd(date);
    }
    // 辅助方法：查询产品模型，返回属性元信息（标识符 -> 名称、单位、数据类型）
    private Map<String, PropertyMeta> getProductPropertyMeta(String productId) {
        Map<String, PropertyMeta> metaMap = new HashMap<>();
        try {
            // 调用华为云SDK查询产品详情（包含产品模型）
            ShowProductRequest request = new ShowProductRequest();
            request.setProductId(productId);
            ShowProductResponse response = client.showProduct(request);

            // 遍历产品模型中的服务和属性，提取元信息
            if (response.getServiceCapabilities() != null) {
                response.getServiceCapabilities().forEach(service -> {
                    if (service.getProperties() != null) {
                        for (ServiceProperty property : service.getProperties()) {
                            String identifier = property.getPropertyName(); // 属性标识符（与设备影子中的key对应）
                            String name = property.getDescription(); // 属性显示名称（如“体温”）
                            String unit = property.getUnit(); // 单位（如“℃”）
                            String dataType = convertDataType(property.getDataType()); // 数据类型（转换为自定义格式）
                            metaMap.put(identifier, new PropertyMeta(name, unit, dataType));
                        }
                    }
                });
            }
        } catch (Exception e) {
            throw new RuntimeException("查询产品模型失败：" + e.getMessage(), e);
        }
        return metaMap;
    }

    // 辅助方法：将华为云数据类型转换为自定义需要的格式（如“float”“int”）
    private String convertDataType(String huaweiType) {
        if (huaweiType == null) {
            return "string";
        }
        switch (huaweiType.toLowerCase()) {
            case "int32":
            case "int64":
                return "int";
            case "float":
            case "double":
                return "float";
            case "string":
                return "string";
            case "boolean":
                return "boolean";
            default:
                return "string"; // 默认为字符串类型
        }
    }

    // 内部类：存储属性元信息（名称、单位、数据类型）

    /**
     * 新增或修改用户
     *
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int) (Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index) + phone.substring(phone.length() - 4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
